import tablib
from import_export import resources
from weixing.models import *
from import_export.fields import Field


class WeixingResource(resources.ModelResource):
    def __init__(self, input_contract=None):
        super(WeixingResource, self).__init__()
        field_list = test._meta.fields
        self.verbose_name_dict = {}
        for i in field_list:
            self.verbose_name_dict[i.name] = i.verbose_name

        # 默认导入导出field的column_name为字段的名称，这里修改为字段的verbose_name

    def get_export_fields(self):
        fields = self.get_fields()
        for field in fields:
            field_name = self.get_field_name(field)
            # 如果有设置 verbose_name，则将 column_name 替换为 verbose_name, 否则维持原有的字段名。
            if field_name in self.verbose_name_dict.keys():
                field.column_name = self.verbose_name_dict[field_name]
        return fields

    # def export(self, queryset=None, *args, **kwargs):
    #
    #     # choices字段显示文字
    #
    #     self.before_export(queryset, *args, **kwargs)
    #
    #     if queryset is None:
    #         queryset = self.get_queryset()
    #     headers = self.get_export_headers()
    #     data = tablib.Dataset(headers=headers)
    #
    #     for obj in self.iter_queryset(queryset):
    #         # 个性化显示 choice 的值
    #         # obj.gender = gender_choice[obj.gender]
    #         obj.sex = obj.get_sex_display()
    #         obj.department_committee = obj.get_department_committee_display()
    #         obj.class_committee = obj.get_class_committee_display()
    #         data.append(self.export_resource(obj))
    #
    #     self.after_export(queryset, data, *args, **kwargs)
    #
    #     return data

    class Meta:
        model = test
        fields = ('name', 'stu')
        export_order = ('name', 'stu')
        exclude = ['id']
        import_id_fields = ['name']


